//
//  BLActionSheet.m
//  EClub
//
//  Created by iBenz on 16/10/28.
//  Copyright © 2016年 EC. All rights reserved.
//

#import "BLActionSheet.h"
#define kSheetItemHeight 47
#define HEXColor(rgbValue) [UIColor colorWithRed : ((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 green : ((float)((rgbValue & 0xFF00) >> 8)) / 255.0 blue : ((float)(rgbValue & 0xFF)) / 255.0 alpha : 1]
#define kHighLightColor HEXColor(0x1E223F)
#define kNormalColor HEXColor(0xffffff)

NS_INLINE UIImage *ColorImage(UIColor *color) {
    CGRect rect = CGRectZero;
    rect.size = (CGSize){1,1};
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@interface BLActionSheet ()
{
    UIView *_boardView;
    UIButton *_cancelBtn;
    UIColor *_separateLineColor;
}
@property (nonatomic, strong,readwrite) NSMutableArray *buttons;
@property (nonatomic, strong,readwrite) NSMutableArray *separaters;
@end

@implementation BLActionSheet

- (void)dealloc {
    NSLog();
}

- (instancetype)initWithTitle:(NSString *)title delegate:(id<BLActionSheetDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... {
    CGRect frame = [UIScreen mainScreen].bounds;
    self = [super initWithFrame:frame];
    if (self) {
        _delegate = delegate;
        self.buttons = [NSMutableArray arrayWithCapacity:0];
        _boardView = [[UIView alloc] initWithFrame:frame];
        _boardView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_boardView];
        
//        _boardView.clipsToBounds = YES;
//        _boardView.layer.masksToBounds = YES;
//        _boardView.layer.cornerRadius = 8.0;
        
        _separateLineColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
        
        NSMutableArray *titles = [NSMutableArray arrayWithCapacity:0];
        
        if (otherButtonTitles) {
            [titles addObject:otherButtonTitles];
            
            NSString *title;
            
            va_list args;
            va_start(args, otherButtonTitles);
            while ((title=(va_arg(args,id)))) {
                [titles addObject:title];
            }
        }
        if (cancelButtonTitle) {
            [titles addObject:cancelButtonTitle];
        }
        
        NSInteger btns = titles.count;
        if (btns) { // 有按钮
            for (NSInteger i=0; i<btns; i++) {
                BLActionSheetItem *btn = [self createSheetItemWithTitle:titles[i] index:i];
                [self addButtonItem:btn];
            }
            
            if (cancelButtonTitle) {
                NSInteger idx = [titles indexOfObject:cancelButtonTitle];
                _cancelBtn = _buttons[idx];
            }
        }
        
        // title
        if (title) {
            _titleLabel = [self Label:[UIFont systemFontOfSize:17]];
            _titleLabel.textColor = kHighLightColor;
        }
    }
    
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    if (!CGRectContainsPoint(_boardView.frame, location)) {
        [self disAnimation];
    }
}

#pragma mark - Public methods

- (void)showInView:(UIView *)view {
    if (!view) {
        view = [[UIApplication sharedApplication].delegate window];
    }
    self.frame = view.bounds;
    [self reloadData];
    [self reloadUI];
    
    self.backgroundColor = [UIColor clearColor];
    [view addSubview:self];
    [self animation];
    
    //[_boardView shakeScaleCompletion:^{
    //}];
}

- (void)dismissAlertView {
    [self disAnimation];
}

#pragma mark - Private methods

- (BLActionSheetItem *)createSheetItemWithTitle:(NSString *)title index:(NSInteger)index {
    BLActionSheetItem *b = nil;
    if ([_delegate respondsToSelector:@selector(actionSheet:sheetAtIndex:)]) {
        b = [_delegate actionSheet:self sheetAtIndex:index];
    }
    else {
        b = [BLActionSheetItem sheetItemWithTitle:title];
    }
    return b;
}

- (void)reloadData {
    CGSize size;
    for (NSInteger idx=0; idx<_buttons.count; idx++) {
        BLActionSheetItem *item = _buttons[idx];
        if ([_delegate respondsToSelector:@selector(actionSheet:heightForSheetAtIndex:)]) {
            size.height = [_delegate actionSheet:self heightForSheetAtIndex:idx];
        }
        else {
            size.height = kSheetItemHeight;
        }
        CGRect frame = item.frame;
        frame.size = size;
        item.frame = frame;
    }
}

- (void)reloadUI {
    @autoreleasepool {
        [_separaters makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_separaters removeAllObjects];
    }
    CGFloat ory = 0.0;
    CGFloat width = CGRectGetWidth(super.bounds);
    if (_titleLabel) {
        CGFloat spacing = 5.0;
        CGRect frame = _titleLabel.frame;
        CGSize size = [_titleLabel sizeThatFits:(CGSize){width-30, CGFLOAT_MAX}];
        size.height += spacing*2;
        frame.size = size;
        _titleLabel.frame = frame;
        CGPoint center = _titleLabel.center;
        center.x = _boardView.layer.position.x;
        _titleLabel.center = center;
        UIView *line = [self separateLine];
        frame = line.frame;
        frame.origin.y = CGRectGetMaxY(_titleLabel.frame)+spacing;
        line.frame = frame;
        [_boardView addSubview:line];
        [self.separaters addObject:line];
        ory = CGRectGetMaxY(line.frame);
    }
    
    for (BLActionSheetItem *item in _buttons) {
        CGRect frame = item.frame;
        frame.origin.y = ory;
        frame.size.width = width;
        item.frame = frame;
        if (item.superview!=_boardView) {
            [_boardView addSubview:item];
        }
        
        if (item!=_buttons.lastObject) {
            UIView *line = [self separateLine];
            frame = line.frame;
            frame.origin.y = CGRectGetMaxY(item.frame);
            line.frame = frame;
            [_boardView addSubview:line];
            [self.separaters addObject:line];
            ory = CGRectGetMaxY(line.frame);
        }
    }
    
    CGRect frame = _boardView.frame;
    frame.size = (CGSize){width, CGRectGetMaxY([_buttons.lastObject frame])};
    _boardView.frame = frame;
}

- (NSInteger)addButtonWithTitle:(nullable NSString *)title {
    NSInteger index = _cancelBtn?[_buttons indexOfObject:_cancelBtn]:_buttons.count;
    BLActionSheetItem *btn = [self createSheetItemWithTitle:title index:index];
    return [self addButtonItem:btn];
}

- (NSInteger)addButtonItem:(BLActionSheetItem *)item {
    [item addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    NSInteger index = _cancelBtn?[_buttons indexOfObject:_cancelBtn]:_buttons.count;
    if (_cancelBtn) {
        [self.buttons insertObject:item atIndex:index];
    }
    else {
        [self.buttons addObject:item];
    }
    return [self.buttons indexOfObject:item];
}

- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex {
    BLActionSheetItem *item = [self buttonWithIndex:buttonIndex];
    return item.titleLabel.text;
}

- (BLActionSheetItem *)buttonWithIndex:(NSInteger)index {
    if (index<0 || index>=_buttons.count) {
        return nil;
    }
    return _buttons[index];
}

- (void)click:(UIButton *)btn {
    if ([_delegate respondsToSelector:@selector(actionSheet:clickedButtonAtIndex:)]) {
        NSInteger index = [_buttons indexOfObject:btn];
        [_delegate actionSheet:self clickedButtonAtIndex:index];
    }
    [self dismissAlertView];
}

- (CGRect)frame {
    return _boardView.frame;
}

- (CGRect)bounds {
    return _boardView.bounds;
}

- (NSInteger)cancelButtonIndex {
    if (!_cancelBtn) {
        return NSNotFound;
    }
    return [_buttons indexOfObject:_cancelBtn];
}

- (UIView *)separateLine {
    UIView *line = [[UIView alloc] initWithFrame:(CGRect){0,0, CGRectGetWidth(self.bounds), 1/[UIScreen mainScreen].scale}];
    line.backgroundColor = _separateLineColor;
    return line;
}

- (UILabel *)Label:(UIFont *)font {
    CGRect frame = self.bounds;
    frame.size.width -= (30);
    UILabel *l = [[UILabel alloc] initWithFrame:frame];
    l.numberOfLines = CGFLOAT_MAX;
    l.lineBreakMode = NSLineBreakByCharWrapping;
    l.clipsToBounds = NO;
    l.font = font;
    return l;
};

- (void)animation {
    CGRect frame = _boardView.frame;
    frame.origin.y = CGRectGetMaxY(super.bounds);
    _boardView.frame = frame;
    frame.origin.y = CGRectGetHeight(super.bounds)-CGRectGetHeight(_boardView.frame);
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        self->_boardView.frame = frame;
    } completion:nil];
}

- (void)disAnimation {
    CGRect frame = _boardView.frame;
    frame.origin.y = CGRectGetMaxY(super.bounds);
    
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
        self->_boardView.frame = frame;
    } completion:^(BOOL finished) {
        self.delegate = nil;
        @autoreleasepool {
            [self removeFromSuperview];
        }
    }];
}

- (NSMutableArray *)buttons {
    if (!_buttons) {
        _buttons = [NSMutableArray arrayWithCapacity:0];
    }
    return _buttons;
}

- (NSMutableArray *)separaters {
    if (!_separaters) {
        _separaters = [NSMutableArray arrayWithCapacity:0];
    }
    return _separaters;
}

@end


@implementation BLActionSheetItem
+ (instancetype)sheetItemWithTitle:(NSString *)title {
    BLActionSheetItem *b = [self buttonWithType:UIButtonTypeCustom];
    [b setTitleColor:kNormalColor forState:UIControlStateNormal];
    [b setBackgroundImage:ColorImage(kHighLightColor) forState:UIControlStateNormal];
    [b setBackgroundImage:ColorImage(HEXColor(0x191D2E)) forState:UIControlStateHighlighted];
    [b setTitle:title forState:UIControlStateNormal];
    return b;
}
@end
